<?php
namespace Modules\Code\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Code\Entities\Code;
use Modules\Product\Entities\Sku;

use Validator;
use ThrowException;
use Auth;
use DB;

class CodeController extends Controller
{
    // 兑换码点击兑换时查看详情
    public function check(Request $req)
    {
        $rule = [
            'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        $info = $req->all();

        $code = Code::where('code', $req->code)->first() ?: ThrowException::Conflict('兑换码不存在');

        $code->status === 0 && ThrowException::Conflict('兑换码已下架~');
        $code->stock <= 0 && ThrowException::Conflict('此码兑换次数已用尽~');
        $code->checkUse($user) && ThrowException::Conflict('您已兑换过此码了哦~');

        $info = [
            'code_type' => $code->code_type,
            'prize_total' => $code->prize_total,
            'score' => $code->score,
            'redpack' => $code->redpack,
        ];

        if ($code->code_type == 'coupon' && $code->coupon) {
            $info['coupon'] = [
                'id' => $code->coupon->id,
                'uuid' => $code->coupon->uuid
            ];
        }
        elseif ($code->code_type == 'chip' && $code->chip) {
            $info['chip'] = [
                'id' => $code->chip->id,
                'uuid' => $code->chip->uuid,
                'title' => $code->chip->title
            ];
        }
        elseif ($code->code_type === 'product') {
            $sku = Sku::getEntity([
                'id' => $code->sku_id,
                'with' => ['product'],
            ], false) ?: ThrowException::Conflict('兑换的商品不存在~');

            $info['product'] = [
                'id' => $sku->id,
                'title' => $sku->product->title
            ];
        }

        return $info;
    }

    // 点击确认兑换
    public function use(Request $req)
    {
        $rule = [
            'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        $info = $req->all();

        $code = Code::where('code', $req->code)->first() ?: ThrowException::Conflict('兑换码不存在');

        DB::beginTransaction();

        $code->use($user);

        DB::commit();

        return [];
    }
}
